<template>
  <div class="warehouse-list-container">
    <span style="font-size: 30px; position: relative; top: -10px"
      >用户管理</span
    >
    <el-button @click="openDialog('新增用户')" style="float: right"
      >新增用户</el-button
    >
    <el-divider></el-divider>
    <el-table :data="users" border stripe style="width: 100%">
      <el-table-column prop="userID" label="用户ID"></el-table-column>
      <el-table-column prop="userName" label="用户名"></el-table-column>
      <el-table-column prop="userTrueName" label="真实姓名"></el-table-column>

      <!-- <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="handleEdit(scope.$index, scope.row)"
            >修改</el-button
          >
        </template> 
      </el-table-column> -->
    </el-table>
    <el-divider></el-divider>

    <!-- 添加用户模态框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <el-form :model="userForm" :rules="rules" ref="userForm">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="userPWD">
          <el-input type="password" v-model="userForm.userPWD"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="UserTrueName">
          <el-input v-model="userForm.userTrueName"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select
            v-model="userForm.selectedRoles"
            multiple
            placeholder="请选择角色"
          >
            <el-option
              v-for="role in roles"
              :key="role.rolesID"
              :label="role.rolesName"
              :value="role.rolesID"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import $http from "@/routers/base";
import { Message } from "element-ui";
export default {
  data() {
    return {
      users: [], // 用户列表
      dialogTitle: "添加用户", // 对话框标题
      dialogVisible: false, // 是否显示对话框
      userForm: {
        UserID: "",
        userName: "",
        userPWD: "",
        userTrueName: "",
        selectedRoles: [], // 角色ID数组
      },
      roles: [], // 角色列表
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 15,
            message: "长度在 2 到 15 个字符",
            trigger: "blur",
          },
        ],
        userPWD: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    fetchUsers() {
      $http
        .get("QuanXian/Query")
        .then((response) => {
          this.users = response;
        })
        .catch((error) => {
          Message.error("获取用户列表失败");
          console.error("Error:", error);
        });
    },

    // 打开新增用户的模态框
    openDialog(type) {
      this.dialogTitle = type === "新增用户" ? "新增用户" : "编辑用户";
      this.dialogVisible = true;
      this.fetchRole();
    },
    //添加用户
    submitUser() {
      this.$refs["userForm"].validate((valid) => {
        if (valid) {
          let createUserWithRolesRequest = {
            User: {
              UserName: this.userForm.userName,
              UserPWD: this.userForm.userPWD,
              UserTrueName: this.userForm.userTrueName,
            },
            RoleIds: this.userForm.selectedRoles,
          };
          $http
            .post("QuanXian/CreateUserWithRoles", createUserWithRolesRequest)
            .then(() => {
              this.fetchUsers();
              this.dialogVisible = false;
              Message.success("用户信息和角色已创建");
              (this.userForm.userName = ""),
                (this.userForm.userPWD = ""),
                (this.userForm.userTrueName = "");
            })
            .catch((error) => {
              Message.error("创建用户信息或角色失败");
              console.error("Error:", error);
            });
        }
      });
    },
    // handleEdit(index, row) {
    //   this.dialogTitle = "编辑用户";
    //   this.dialogVisible = true;
    //   this.userForm = { ...row };
    //   this.userForm.selectedRoles = row.selectedRoles || [];
    //   this.fetchRole();
    // },
    fetchRole() {
      $http
        .get("QuanXian/GetAllRoles")
        .then((response) => {
          this.roles = response;
        })
        .catch((error) => {
          Message.error("获取角色列表失败");
          console.error("Error:", error);
        });
    },
  },
  mounted() {
    this.fetchUsers();
  },
};
</script>

<style scoped src="../CSS/SaleOrder.css"></style>
<style scoped>
.el-form-item {
  display: flex;
  align-items: center;
}

.el-form-item label {
  flex: 0 0 30%; /* 设置标签的宽度，根据需要进行调整 */
  text-align: right; /* 将标签文字右对齐 */
  padding-right: 10px; /* 可选：添加右边距 */
}

.el-form-item .el-input {
  flex: 1; /* 让输入框占据剩余的空间 */
}
</style>
